<template>
  <div
    class="merchant-account-settings bg-white dark:bg-gray-800 min-h-screen p-6"
  >
    <a-card class="mb-6">
      <template #title>
        <div class="flex items-center">
          <icon-lock class="mr-2" />
          <span class="text-lg font-medium">修改密码</span>
        </div>
      </template>

      <a-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        layout="vertical"
        class="max-w-lg"
      >
        <a-form-item
          field="currentPassword"
          label="当前密码"
          :rules="[{ required: true, message: '请输入当前密码' }]"
        >
          <a-input-password
            v-model="passwordForm.currentPassword"
            placeholder="请输入当前密码"
          />
        </a-form-item>

        <a-form-item
          field="newPassword"
          label="新密码"
          :rules="[{ required: true, message: '请输入新密码' }]"
        >
          <a-input-password
            v-model="passwordForm.newPassword"
            placeholder="请输入新密码"
          />
        </a-form-item>

        <a-form-item
          field="confirmPassword"
          label="确认新密码"
          :rules="[{ required: true, message: '请确认新密码' }]"
        >
          <a-input-password
            v-model="passwordForm.confirmPassword"
            placeholder="请再次输入新密码"
          />
        </a-form-item>

        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleChangePassword">
              确认修改
            </a-button>
            <a-button @click="resetPasswordForm">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card class="mb-6">
      <template #title>
        <div class="flex items-center">
          <icon-notification class="mr-2" />
          <span class="text-lg font-medium">通知设置</span>
        </div>
      </template>

      <a-form
        ref="notificationFormRef"
        :model="notificationSettings"
        layout="vertical"
      >
        <a-form-item field="orderNotification" label="订单通知">
          <a-switch
            v-model="notificationSettings.orderNotification"
            :checked-text="'开启'"
            :unchecked-text="'关闭'"
          />
          <div class="text-sm text-gray-500 mt-1">
            接收新订单、订单状态变更等通知
          </div>
        </a-form-item>

        <a-form-item field="reviewNotification" label="评价通知">
          <a-switch
            v-model="notificationSettings.reviewNotification"
            :checked-text="'开启'"
            :unchecked-text="'关闭'"
          />
          <div class="text-sm text-gray-500 mt-1">
            接收新的商品评价、回复提醒等通知
          </div>
        </a-form-item>

        <a-form-item field="systemNotification" label="系统通知">
          <a-switch
            v-model="notificationSettings.systemNotification"
            :checked-text="'开启'"
            :unchecked-text="'关闭'"
          />
          <div class="text-sm text-gray-500 mt-1">
            接收系统更新、活动提醒等通知
          </div>
        </a-form-item>

        <a-form-item field="notificationMethods" label="通知方式">
          <a-space direction="vertical">
            <a-checkbox-group
              v-model="notificationSettings.notificationMethods"
            >
              <a-checkbox value="email">
                邮件通知
                <span class="text-sm text-gray-500 ml-2">{{
                  userStore.email
                }}</span>
              </a-checkbox>
              <a-checkbox value="sms">
                短信通知
                <span class="text-sm text-gray-500 ml-2">{{
                  userStore.phone
                }}</span>
              </a-checkbox>
              <a-checkbox value="system">
                站内信通知
                <span class="text-sm text-gray-500 ml-2"
                  >实时推送到消息中心</span
                >
              </a-checkbox>
            </a-checkbox-group>
          </a-space>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSaveNotificationSettings">
            保存设置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card class="mb-6">
      <template #title>
        <div class="flex items-center">
          <icon-settings class="mr-2" />
          <span class="text-lg font-medium">偏好设置</span>
        </div>
      </template>

      <a-form
        ref="preferenceFormRef"
        :model="preferenceSettings"
        layout="vertical"
      >
        <a-form-item field="theme" label="系统主题">
          <a-radio-group v-model="preferenceSettings.theme" type="button">
            <a-radio value="light">浅色</a-radio>
            <a-radio value="dark">深色</a-radio>
            <a-radio value="auto">跟随系统</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item field="language" label="系统语言">
          <a-select v-model="preferenceSettings.language" style="width: 200px">
            <a-option value="zh-CN">简体中文</a-option>
            <a-option value="en-US">English</a-option>
          </a-select>
        </a-form-item>

        <a-form-item field="timezone" label="时区设置">
          <a-select v-model="preferenceSettings.timezone" style="width: 200px">
            <a-option value="Asia/Shanghai">中国标准时间 (UTC+8)</a-option>
            <a-option value="Asia/Tokyo">日本标准时间 (UTC+9)</a-option>
            <a-option value="America/New_York">美国东部时间 (UTC-5)</a-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSavePreferenceSettings">
            保存设置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card class="mb-6">
      <template #title>
        <div class="flex items-center">
          <icon-safe class="mr-2" />
          <span class="text-lg font-medium">安全设置</span>
        </div>
      </template>

      <div class="space-y-6">
        <div class="flex items-center justify-between">
          <div>
            <div class="text-base font-medium">双因素认证</div>
            <div class="text-sm text-gray-500 mt-1">
              启用双因素认证，提高账号安全性
            </div>
          </div>
          <a-switch
            v-model="securitySettings.twoFactorAuth"
            @change="handleTwoFactorAuthChange"
          />
        </div>

        <div class="flex items-center justify-between">
          <div>
            <div class="text-base font-medium">登录通知</div>
            <div class="text-sm text-gray-500 mt-1">异地登录时发送通知提醒</div>
          </div>
          <a-switch
            v-model="securitySettings.loginNotification"
            @change="handleLoginNotificationChange"
          />
        </div>

        <div class="flex items-center justify-between">
          <div>
            <div class="text-base font-medium">登录设备管理</div>
            <div class="text-sm text-gray-500 mt-1">
              查看并管理当前登录的设备
            </div>
          </div>
          <a-button type="text" @click="showDeviceManagementModal = true">
            查看设备
          </a-button>
        </div>
      </div>
    </a-card>

    <a-card>
      <template #title>
        <div class="flex items-center">
          <icon-exclamation-circle class="mr-2" />
          <span class="text-lg font-medium text-danger">账号注销</span>
        </div>
      </template>

      <div class="danger-zone">
        <div class="warning-text">
          <icon-exclamation-circle-fill class="warning-icon" />
          <div class="flex-1">
            <div class="font-medium">注销账号将会：</div>
            <ul class="list-disc list-inside mt-2 space-y-1 text-sm">
              <li>永久删除您的所有商品、订单等数据</li>
              <li>解除与平台的所有合作关系</li>
              <li>无法恢复已删除的数据</li>
            </ul>
          </div>
        </div>
        <a-button status="danger" @click="showDeleteAccountModal = true">
          注销账号
        </a-button>
      </div>
    </a-card>

    <!-- 设备管理弹窗 -->
    <a-modal
      v-model:visible="showDeviceManagementModal"
      title="登录设备管理"
      width="600px"
    >
      <a-table :data="deviceList" :pagination="false">
        <template #columns>
          <a-table-column title="设备信息" data-index="device">
            <template #cell="{ record }">
              <div class="flex items-center">
                <icon-desktop class="mr-2" v-if="record.type === 'desktop'" />
                <icon-mobile
                  class="mr-2"
                  v-else-if="record.type === 'mobile'"
                />
                <icon-tablet class="mr-2" v-else />
                <div>
                  <div>{{ record.name }}</div>
                  <div class="text-sm text-gray-500">{{ record.browser }}</div>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="登录地点" data-index="location" />
          <a-table-column title="最后活动时间" data-index="lastActiveTime" />
          <a-table-column title="操作">
            <template #cell="{ record }">
              <a-button
                v-if="!record.current"
                type="text"
                status="danger"
                @click="handleRemoveDevice(record)"
              >
                移除
              </a-button>
              <a-tag v-else color="green">当前设备</a-tag>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>

    <!-- 注销账号确认弹窗 -->
    <a-modal
      v-model:visible="showDeleteAccountModal"
      title="注销账号确认"
      @ok="handleDeleteAccount"
      @cancel="showDeleteAccountModal = false"
    >
      <a-alert type="warning" class="mb-4">
        <template #message>
          请仔细阅读以下信息：
          <ol class="list-decimal list-inside mt-2">
            <li>账号注销后，所有数据将被永久删除</li>
            <li>账号注销操作不可撤销</li>
            <li>如有未处理的订单或退款，请先处理完成</li>
          </ol>
        </template>
      </a-alert>

      <a-form :model="deleteAccountForm" layout="vertical">
        <a-form-item
          field="password"
          label="请输入登录密码"
          :rules="[{ required: true, message: '请输入登录密码' }]"
        >
          <a-input-password
            v-model="deleteAccountForm.password"
            placeholder="请输入登录密码"
          />
        </a-form-item>

        <a-form-item
          field="confirm"
          :rules="[{ required: true, message: '请确认注销操作' }]"
        >
          <a-checkbox v-model="deleteAccountForm.confirm">
            我已知晓账号注销的所有后果，并确认注销操作
          </a-checkbox>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconLock,
  IconNotification,
  IconSettings,
  IconSafe,
  IconExclamationCircle,
  IconExclamationCircleFill,
  IconDesktop,
  IconMobile,
  IconTablet,
} from "@arco-design/web-vue/es/icon";
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();
const passwordFormRef = ref(null);
const notificationFormRef = ref(null);
const preferenceFormRef = ref(null);

// 密码修改相关
const passwordForm = ref({
  currentPassword: "",
  newPassword: "",
  confirmPassword: "",
});

const passwordRules = {
  currentPassword: [{ required: true, message: "请输入当前密码" }],
  newPassword: [
    { required: true, message: "请输入新密码" },
    { minLength: 8, message: "密码长度不能小于8位" },
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码" },
    {
      validator: (value) => value === passwordForm.value.newPassword,
      message: "两次输入的密码不一致",
    },
  ],
};

// 通知设置相关
const notificationSettings = ref({
  orderNotification: true,
  reviewNotification: true,
  systemNotification: true,
  notificationMethods: ["system"],
});

// 偏好设置相关
const preferenceSettings = ref({
  theme: "light",
  language: "zh-CN",
  timezone: "Asia/Shanghai",
});

// 安全设置相关
const securitySettings = ref({
  twoFactorAuth: false,
  loginNotification: true,
});

// 设备管理相关
const showDeviceManagementModal = ref(false);
const deviceList = ref([
  {
    id: 1,
    type: "desktop",
    name: "Windows 10",
    browser: "Chrome 122.0.6261.112",
    location: "广西贵港",
    lastActiveTime: "2024-03-15 15:30:00",
    current: true,
  },
  {
    id: 2,
    type: "mobile",
    name: "iPhone 13",
    browser: "Safari",
    location: "广西南宁",
    lastActiveTime: "2024-03-14 10:20:00",
    current: false,
  },
]);

// 注销账号相关
const showDeleteAccountModal = ref(false);
const deleteAccountForm = ref({
  password: "",
  confirm: false,
});

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return;

  try {
    await passwordFormRef.value.validate();
    // TODO: 调用修改密码的 API
    Message.success("密码修改成功");
    resetPasswordForm();
  } catch (error) {
    // 表单验证失败
  }
};

// 重置密码表单
const resetPasswordForm = () => {
  if (!passwordFormRef.value) return;
  passwordFormRef.value.resetFields();
};

// 保存通知设置
const handleSaveNotificationSettings = async () => {
  try {
    // TODO: 调用保存通知设置的 API
    Message.success("通知设置保存成功");
  } catch (error) {
    Message.error("通知设置保存失败");
  }
};

// 保存偏好设置
const handleSavePreferenceSettings = async () => {
  try {
    // TODO: 调用保存偏好设置的 API
    Message.success("偏好设置保存成功");
  } catch (error) {
    Message.error("偏好设置保存失败");
  }
};

// 双因素认证变更
const handleTwoFactorAuthChange = async (value) => {
  try {
    // TODO: 调用更新双因素认证状态的 API
    Message.success(value ? "双因素认证已开启" : "双因素认证已关闭");
  } catch (error) {
    securitySettings.value.twoFactorAuth = !value;
    Message.error("设置更新失败");
  }
};

// 登录通知变更
const handleLoginNotificationChange = async (value) => {
  try {
    // TODO: 调用更新登录通知状态的 API
    Message.success(value ? "登录通知已开启" : "登录通知已关闭");
  } catch (error) {
    securitySettings.value.loginNotification = !value;
    Message.error("设置更新失败");
  }
};

// 移除设备
const handleRemoveDevice = async (device) => {
  try {
    // TODO: 调用移除设备的 API
    deviceList.value = deviceList.value.filter((item) => item.id !== device.id);
    Message.success("设备已移除");
  } catch (error) {
    Message.error("设备移除失败");
  }
};

// 注销账号
const handleDeleteAccount = async () => {
  if (!deleteAccountForm.value.confirm) {
    Message.error("请确认注销操作");
    return;
  }

  try {
    // TODO: 调用注销账号的 API
    Message.success("账号已注销");
    await userStore.logout();
    router.push("/login");
  } catch (error) {
    Message.error("账号注销失败");
  }
};
</script>

<style lang="scss" scoped>
.merchant-account-settings {
  max-width: 1200px;
  margin: 0 auto;

  :deep(.arco-card) {
    background-color: var(--color-bg-2);
    border-color: var(--color-border);
  }

  :deep(.arco-form-item-label) {
    font-weight: 500;
  }

  .danger-zone {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 16px;
    background-color: var(--color-danger-light-1);
    border-radius: 4px;

    .warning-text {
      display: flex;
      align-items: flex-start;
      color: rgb(var(--danger-6));
      flex: 1;
      margin-right: 16px;

      .warning-icon {
        margin-right: 8px;
        margin-top: 3px;
        font-size: 20px;
        flex-shrink: 0;
      }
    }
  }

  :deep(.arco-modal) {
    .arco-modal-header {
      border-bottom: 1px solid var(--color-border);
    }

    .arco-modal-footer {
      border-top: 1px solid var(--color-border);
    }
  }

  :deep(.arco-table) {
    .arco-table-th {
      background-color: var(--color-fill-2);
    }

    .arco-table-tr:hover {
      background-color: var(--color-fill-2);
    }
  }

  @media (max-width: 640px) {
    .danger-zone {
      flex-direction: column;
      align-items: stretch;

      .warning-text {
        margin-right: 0;
        margin-bottom: 16px;
      }
    }
  }
}
</style>
